﻿using Sui.Domain.App;
using Dotnet.Code;
using Dotnet.Code.Extend;
using Dotnet.FormExtensions;
using ScrapySharp.Html;
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Linq;
using Dotnet.Sui;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Dotnet.TopApi.Request;
using Dotnet.TopApi;
using System.IO;
using System.Diagnostics;
using Dotnet.FormExtensions.UsrControl;

namespace Sui.WinForm
{
    public partial class FrmZfb : Form
    {
        private const string Pwd = "xyz62411570*";
        private Dictionary<string, string> _dict = new Dictionary<string, string>();
        private DataTable _dataTable = new DataTable();
        public FrmZfb()
        {
            InitializeComponent();
            ucDgvMain.DataGridView.DataSourceChanged += DataGridView_DataSourceChanged;
            ucDgvSum.CheckBoxStateChange += UcDgvSum_CheckBoxStateChange;
            ucDgvMain.ToolStripMenuItemClick += UcDgvMain_ToolStripMenuItemClick;
            dtpStart.CustomFormat = "yyyy-MM-dd";
            dtpStart.Value = new DateTime(2021,01,01);
            dtpEnd.CustomFormat = "yyyy-MM-dd";
            txtPwd.Text = Pwd;
            if(File.Exists("Database\\Sui\\cookie.json")){
                txtCookie.Text = File.ReadAllText("Database\\Sui\\cookie.json"); 
            }
        }



        private void UcDgvMain_ToolStripMenuItemClick(object sender, ToolStripMenuItemClickEventArgs e)
        {
            Dotnet.Sui.Sui sui = new Dotnet.Sui.Sui(txtCookie.Text.Trim());
            txtShow.Clear();
            try
            {
                string account = GetCmbZh();
                if (string.IsNullOrEmpty(account))
                {
                    MessageBox.Show("账号不能为空"); return;
                }
                string project = (cmbXm.SelectedItem as Account)?.Id;
                string member = (cmbCy.SelectedItem as Account)?.Id;
                string store = (cmbSj.SelectedItem as Account)?.Id;

                switch (e.Name)
                {
                    case "随手收":
                        foreach (DataGridViewRow item in ucDgvMain.DataGridView.SelectedRows)
                        {
                            string incomeCategory = GetCmbSr();
                            if (string.IsNullOrEmpty(incomeCategory))
                            {
                                MessageBox.Show("收入分类不能为空"); return;
                            }
                            string price = item.Cells["金额"].Value.ToString();
                            string time = item.Cells["创建时间"].Value.ToString();
                            string jjdf = item.Cells["交易对方"].Value.ToString();
                            string spmc = item.Cells["商品名称"].Value.ToString();
                            string id = item.Cells["id"].Value.ToString();
                            string memo = $"自收:{id}:{jjdf}:{spmc}";
                            bool isSucc = sui.Sui收(id, incomeCategory, account, price, time,
                                memo, project, member, store, (str) =>
                                {
                                    txtShow.AppendTextAsync(str);
                                });
                        }
                        break;
                    case "随手付":
                        foreach (DataGridViewRow item in ucDgvMain.DataGridView.SelectedRows)
                        {
                            string budgetCategory = GetCmbZc();
                            if (string.IsNullOrEmpty(budgetCategory))
                            {
                                MessageBox.Show("支出分类不能为空"); return;
                            }
                            string price = item.Cells["金额"].Value.ToString();
                            string time = item.Cells["创建时间"].Value.ToString();
                            string jjdf = item.Cells["交易对方"].Value.ToString();
                            string spmc = item.Cells["商品名称"].Value.ToString();
                            string id = item.Cells["id"].Value.ToString();
                            string memo = $"自支:{id}:{jjdf}:{spmc}";
                            bool isSucc = sui.Sui支(id, budgetCategory, account, price, time,memo, project, member, store, (str) =>
                            {
                                txtShow.AppendTextAsync(str);
                            });
                        }
                        break;
                    case "随手转":
                        foreach (DataGridViewRow item in ucDgvMain.DataGridView.SelectedRows)
                        {
                            string out_account = "17273911133";
                            string in_account = account;
                            string price = item.Cells["金额"].Value.ToString();
                            string time = item.Cells["创建时间"].Value.ToString();
                            string jjdf = item.Cells["交易对方"].Value.ToString();
                            string spmc = item.Cells["商品名称"].Value.ToString();
                            string id = item.Cells["id"].Value.ToString();
                            string memo = $"自转:{id}:{jjdf}:{spmc}";
                            bool isSucc = sui.Sui转(id, out_account, account, price, time, memo, project, member, store, (str) =>
                            {
                                txtShow.AppendTextAsync(str);
                            });
                        }
                        break;
                    case "求和":
                        decimal sum = ucDgvMain.DataGridView.SelectedRows.Cast<DataGridViewRow>().Sum(t => Decimal.Parse(t.Cells["金额"].Value.ToString()));
                        string info = $"选中记录数:{ucDgvMain.DataGridView.SelectedRows.Count} 汇总值:{sum}";
                        txtShow.AppendTextAsync(info); break;
                }
            }
            catch (Exception ex)
            {
                txtShow.AppendTextAsync($"{ex.Message}\r\n{ex.StackTrace}");
            }
           
        }

        private void DataGridView_DataSourceChanged(object sender, EventArgs e)
        {
            List<string> list=new List<string>();
            list.Add("收支"); list.Add("交易状态"); list.Add("资金状态");
            ucDgvSum.GroupSumColumns  = list;
            ucDgvSum.DataSource = _dataTable;
            string info = $"总条数：{_dataTable.Rows.Count} 汇总数据：{ucDgvSum.GroupSumDataTable.Rows.Count} 条\r\n==============";
            txtShow.AppendTextAsync(info,false);
        }
        private void UcDgvSum_CheckBoxStateChange(object sender, EventArgs e)
        {
            string info = $"总条数：{_dataTable.Rows.Count} 汇总数据：{ucDgvSum.GroupSumDataTable.Rows.Count} 条\r\n==============";
            txtShow.AppendTextAsync(info, false);
        }

        private void FrmZfb_Load(object sender, EventArgs e)
        {
        }
        private void btnRefresh_Click(object sender, EventArgs e)
        {
            if (txtPwd.Text != Pwd)
            {
                txtShow.AppendText("密码不正确");
                return;
            }
            ZfbApp app = new ZfbApp();
            DataTable dt = app.GetDataTable("Zfb");
            dt.DefaultView.Sort = "创建时间 DESC";
            dt = dt.DefaultView.ToTable();
            ucDgvMain.DataSource = dt;
            SetDgvColumnWidth();
        }
        private void btnAddSub_Click(object sender, EventArgs e)
        {
            ClearControlText();
            Button btn = sender as Button;
            DateTime d1 = dtpStart.Value;
            DateTime d2 = dtpEnd.Value;
            int day = d2.Subtract(d1).Days;
            if (btn.Text == "+")
            {
                if (radD.Checked)
                {
                    dtpStart.Value = dtpStart.Value.AddDays(1);
                    dtpEnd.Value = dtpStart.Value;
                }
                else if (radM.Checked)
                {
                    DateTime originalDate = new DateTime(dtpStart.Value.Year, dtpStart.Value.Month, dtpStart.Value.Day); // 示例日期
                    DateTime newDateStart = originalDate.AddMonths(1).AddDays(1 - originalDate.Day);
                    DateTime newDateEnd = new DateTime(newDateStart.Year, newDateStart.Month, DateTime.DaysInMonth(newDateStart.Year, newDateStart.Month));
                    dtpStart.Value = newDateStart;
                    dtpEnd.Value = newDateEnd;
                }
                else if (radY.Checked)
                {
                    DateTime originalDate = new DateTime(dtpStart.Value.Year, dtpStart.Value.Month, dtpStart.Value.Day); // 示例日期
                    DateTime newStartDate = new DateTime(originalDate.AddYears(1).Year, 1, 1);
                    DateTime newEndDate = new DateTime(newStartDate.Year, 12, 31);
                    dtpStart.Value = newStartDate;
                    dtpEnd.Value = newEndDate;
                }
                else
                {
                    dtpStart.Value = dtpStart.Value.AddDays(day + 1);
                    dtpEnd.Value = dtpEnd.Value.AddDays(day + 1);
                }
            }
            if (btn.Text == "-")
            {
                if (radD.Checked)
                {
                    dtpStart.Value = dtpEnd.Value.AddDays(-1);
                    dtpEnd.Value = dtpStart.Value;
                }
                else if (radM.Checked)
                {
                    DateTime originalDate = new DateTime(dtpEnd.Value.Year, dtpEnd.Value.Month, dtpStart.Value.Day); // 示例日期
                    DateTime newDateStart = originalDate.AddMonths(-1).AddDays(1 - originalDate.Day);
                    DateTime newDateEnd = new DateTime(newDateStart.Year, newDateStart.Month, DateTime.DaysInMonth(newDateStart.Year, newDateStart.Month));
                    dtpStart.Value = newDateStart;
                    dtpEnd.Value = newDateEnd;
                }
                else if (radY.Checked)
                {
                    DateTime originalDate = new DateTime(dtpEnd.Value.Year, dtpStart.Value.Month, dtpEnd.Value.Day); // 示例日期
                    DateTime newStartDate = new DateTime(originalDate.AddYears(-1).Year,1,1);
                    DateTime newEndDate = new DateTime(newStartDate.Year, 12, 31);
                    dtpStart.Value = newStartDate;
                    dtpEnd.Value = newEndDate;
                }
                else
                {
                    dtpStart.Value = dtpStart.Value.AddDays(day - 1);
                    dtpEnd.Value = dtpEnd.Value.AddDays(day - 1);
                }
            }
            btnFind_Click(sender, e);
        }
        
        private void btnFind_Click(object sender, EventArgs e)
        {
            if (txtPwd.Text != Pwd)
            {
                txtShow.AppendText("密码不正确");
                return;
            }
            txtShow.Clear();
            string sql = "";
            if (!string.IsNullOrEmpty(txtShow2.Text))
            {
                string tmp = txtShow2.Text.Trim();
                if (tmp.StartsWith("select")) sql = tmp;
                else if (tmp.StartsWith("delete")) sql = tmp;
                else if (tmp.StartsWith("update")) sql = tmp;
            }
            if(string.IsNullOrEmpty(sql)) sql = GetUserSelectSql();
            ZfbApp app = new ZfbApp();
            txtShow.AppendTextAsync(sql + "\r\n=================", false);   
            _dataTable = app.GetDataTableBySql(sql);
            ucDgvMain.DataSource = null;
            ucDgvMain.DataSource = _dataTable;
            // SetDgvColumnWidth();
            txtShow2.Clear();
        }
        Stopwatch sw = Stopwatch.StartNew();
        private void btnDrzd_Click(object sender, EventArgs e)
        {
            OpenFileDialog ofd = new OpenFileDialog();
            txtShow.Clear();
            ofd.Filter = "Excel文件(*.xls)|*.xls|Excel文件(*.xlsx)|*.xlsx|所有文件(*.*)|*.*";
            try
            {
                if (string.IsNullOrEmpty(cmbLyd.Text))
                {
                    MessageBox.Show("请选择导入数据来源地(ZFB,WX,LD)"); return;
                }
                string excelType=cmbLyd.Text.Trim();
                if (ofd.ShowDialog() == DialogResult.OK)
                {
                    string fileName = ofd.FileName;
                    this.Text= fileName;
                    btnDrzd.Enabled = false;
                    BaseExcel xls = BaseExcel.Create(fileName, excelType);
                    if (xls == null)
                    {
                        MessageBox.Show("请选择导入数据来源地(ZFB,WX,LD)"); return;
                    }
                    int updateRows = 0, insertRows = 0;
                    xls.ExcelToTable += (sender1,ee) => {
                        ZfbApp app = new ZfbApp();
                        string type = "";
                        int ret = app.Save(ee.CurrDataRow, out type, excelType);
                        if (type == "Update") updateRows++;
                        if (type == "Insert") insertRows++;
                        string sheetInfo = $"【工作薄数】{ee.SheetCount} 【当前第:{ee.CurrWorkSheet.Index + 1}】{ee.CurrWorkSheet.Name}";
                        string info = $"【{type}:{ret}】 更新:{updateRows} 插入:{insertRows} 总记录:{ee.SheetRowsCount} 已处理:{ee.Index} 剩余:{ee.SheetRowsCount - ee.Index} " +
                            $"耗时:{sw.Elapsed.TotalSeconds.ToString("N2")}" +
                            $"【{ee.CurrDataRow[0].ToString()}：{ee.CurrDataRow[2]}：{ee.CurrDataRow[9]}】";
                        txtShow.AppendTextAsync($"{sheetInfo} {info}",false);
                        if (ret == 0) { 
                            LogFactory.GetLogger("FrmZfb").Error(info);
                        }
                    };
                    string password = txtPwd.Text.Trim();
                    Task.Factory.StartNew(() => {
                        sw.Restart();
                        xls.ExcelToDataTable(password);
                    }).ContinueWith(t=>{
                        if(t.IsFaulted)
                        {
                            string info = $"{t.Exception.InnerException.Message}\r\n{t.Exception.InnerException.StackTrace}";
                            txtShow.AppendTextAsync(info);
                        }
                        btnDrzd.SetButtonEnableAsync(true);
                        sw.Stop();
                    });
                }
            }
            catch(Exception ex)
            {
                txtShow.AppendTextAsync(ex.Message);
            }
        }


        private void btnSui_Click(object sender, EventArgs e)
        {
            //var xx = ucDgvMain.DataGridView.ContextMenuStrip.Items;
            //Sui sui = new Sui(txtCookie.Text);
            //ZfbApp app = new ZfbApp();
            //DataTable dt= app.GetDataTableBySql("select *from Zfb where 1==0");
            //try
            //{
            //    Task.Factory.StartNew(()=> {
            //        sui.TallyNewList2(dtpStart.Value, dtpEnd.Value, (tallyAccountList, info) => {
            //            dt.Rows.Clear();
            //            foreach (TallyAccount account in tallyAccountList)
            //            {
            //                DataRow dr = dt.NewRow();
            //                dr["id"] = account.sId;
            //                dr["创建时间"] = account.date.time.UnixTimeToDateTime();
            //                dr["收支"] = account.tranName;
            //                dr["金额"] = account.itemAmount;
            //                dr["来源地"] = "随手记";
            //                dr["类型"] = account.account + ":" + account.buyerAcount;//账号
            //                dr["交易对方"] = account.categoryId + ":" + account.categoryName;//分类
            //                dr["商品名称"] = account.projectId + ":" + account.projectName;//项目
            //                dr["订单号"] = account.sellerAcountId + ":" + account.sellerAcount;//商家
            //                dr["备注"] = account.memo;
            //                dt.Rows.Add(dr);
            //            }
            //            app.Save(dt, (str) =>
            //            {
            //                txtShow.AppendTextAsync($"{info}—【{str}】");
            //            });
            //        });
            //    });
                
                //List<Account> list1 = sui.GetSuiAccountCategory(AccountCate.ZH);
                //List<Account> list2 = sui.GetSuiAccountCategory(AccountCate.ZC);
                //txtShow.AppendTextAsync(list1.ToJson()+"\r\n"+list2.ToJson());
            //}
            //catch (Exception ex)
            //{
            //    txtShow.AppendTextAsync(ex.Message);
            //}
        }
        private void btnClear_Click(object sender, EventArgs e)
        {
            ClearControlText();
        }

        private void 求和ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            //decimal sum = dgvSum.SelectedRows.Cast<DataGridViewRow>().Sum(t => Decimal.Parse(t.Cells["汇总"].Value.ToString()));
            //string info = $"【选中记录数】:{dgvSum.SelectedRows.Count} 总值:{sum}";
            //txtShow.AppendTextAsync(info);
        }
        #region 同步随
        private void btnTb_Click(object sender, EventArgs e)
        {
            txtShow.Clear();
            try
            {
                TallyNewRmiRequest req = new TallyNewRmiRequest();
                req.Cookie = txtCookie.Text.Trim();
                SuiClient client = new SuiClient();
                TallyNewRmiResponse resp = client.Execute<TallyNewRmiResponse>(req);
                txtShow.AppendText($"【{resp.ReqUrl}】===============\r\n{resp.Body}\r\n");
                if (resp.Body.StartsWith("{error")) return;

                System.IO.File.WriteAllText("Database\\Sui\\cookie.json", txtCookie.Text.Trim());
                Dotnet.Sui.Sui sui = new Dotnet.Sui.Sui();
                sui.SuiCateAccountSame(txtCookie.Text.Trim(), (suiDoResp) =>
                {
                    txtShow.AppendText($"【{suiDoResp.ReqUrl}】===============\r\n{suiDoResp.CateAccount.ToJson()}\r\n");
                    InitCateAccountComboBox(suiDoResp.ReqUrl, suiDoResp.CateAccount);
                    WriteCateAccountToFile(suiDoResp.ReqUrl, suiDoResp.CateAccount);
                });
            }
            catch (Exception ex)
            {
                txtShow.AppendText($"【{ex.Message}】===============\r\n{ex.StackTrace}\r\n");
            }

        }
        private void InitCateAccountComboBox(string url,List<Account> cateAccount)
        {
            if (url.Contains("account.do"))
            {
                cmbZh1.SelectedIndexChanged -= cmbSui_SelectedIndexChanged;
                cmbZh1.DataSource = cateAccount;
                cmbZh1.DisplayMember = "Name"; // 显示的属性
                cmbZh1.ValueMember = "Id"; // 实际值的属性
                cmbZh1.SelectedIndexChanged += cmbSui_SelectedIndexChanged;
            }
            else if (url.Contains("budgetCategory.do"))
            {
                cmbZc1.SelectedIndexChanged -= cmbSui_SelectedIndexChanged;
                cmbZc1.DataSource = cateAccount;
                cmbZc1.DisplayMember = "Name"; // 显示的属性
                cmbZc1.ValueMember = "Id"; // 实际值的属性
                cmbZc1.SelectedIndexChanged += cmbSui_SelectedIndexChanged;
            }
            else if (url.Contains("incomeCategory.do"))
            {
                cmbSr1.SelectedIndexChanged -= cmbSui_SelectedIndexChanged;
                cmbSr1.DataSource = cateAccount;
                cmbSr1.DisplayMember = "Name"; // 显示的属性
                cmbSr1.ValueMember = "Id"; // 实际值的属性
                cmbSr1.SelectedIndexChanged += cmbSui_SelectedIndexChanged;
            }
            else if (url.Contains("member.do"))
            {
                cmbCy.SelectedIndexChanged -= cmbSui_SelectedIndexChanged;
                cmbCy.DataSource = cateAccount;
                cmbCy.DisplayMember = "Name"; // 显示的属性
                cmbCy.ValueMember = "Id"; // 实际值的属性
                cmbCy.SelectedIndexChanged += cmbSui_SelectedIndexChanged;
            }
            else if (url.Contains("projectCategory.do"))
            {
                cmbXm.SelectedIndexChanged -= cmbSui_SelectedIndexChanged;
                cmbXm.DataSource = cateAccount;
                cmbXm.DisplayMember = "Name"; // 显示的属性
                cmbXm.ValueMember = "Id"; // 实际值的属性
                cmbXm.SelectedIndexChanged += cmbSui_SelectedIndexChanged;
            }
            else if (url.Contains("storeCategory.do"))
            {
                cmbSj.SelectedIndexChanged -= cmbSui_SelectedIndexChanged;
                cmbSj.DataSource = cateAccount;
                cmbSj.DisplayMember = "Name"; // 显示的属性
                cmbSj.ValueMember = "Id"; // 实际值的属性
                cmbSj.SelectedIndexChanged += cmbSui_SelectedIndexChanged;
            }
            else
            {

            }
        }
        private void WriteCateAccountToFile(string url, List<Account> cateAccount)
        {
            string dir = $"{Application.StartupPath}\\Database\\Sui\\do.cate.account";
            if (url.Contains("account.do"))
            {
                File.WriteAllText($"{dir}\\account.do",cateAccount.ToJson());
            }
            else if (url.Contains("budgetCategory.do"))
            {
                File.WriteAllText($"{dir}\\budgetCategory.do", cateAccount.ToJson());
            }
            else if (url.Contains("incomeCategory.do"))
            {
                File.WriteAllText($"{dir}\\incomeCategory.do", cateAccount.ToJson());
            }
            else if (url.Contains("member.do"))
            {
                File.WriteAllText($"{dir}\\member.do", cateAccount.ToJson());
            }
            else if (url.Contains("projectCategory.do"))
            {
                File.WriteAllText($"{dir}\\projectCategory.do", cateAccount.ToJson());
            }
            else if (url.Contains("storeCategory.do"))
            {
                File.WriteAllText($"{dir}\\storeCategory.do", cateAccount.ToJson());
            }
            else
            {

            }
        }


        private void cmbSui_SelectedIndexChanged(object sender, EventArgs e)
        {
            ComboBox cmb = sender as ComboBox;
            if (cmb == null) return;
            switch (cmb.Name)
            {
                case "cmbZh1":
                    cmbZh2.DataSource = (cmbZh1.SelectedItem as Account).ChildAccount;
                    cmbZh2.DisplayMember = "Name"; // 显示的属性
                    cmbZh2.ValueMember = "Id"; // 实际值的属性
                    break;
                case "cmbZh2":
                    cmbZh3.DataSource = (cmbZh2.SelectedItem as Account).ChildAccount;
                    cmbZh3.DisplayMember = "Name"; // 显示的属性
                    cmbZh3.ValueMember = "Id"; // 实际值的属性
                    break;
                case "cmbZc1":
                    cmbZc2.DataSource = (cmbZc1.SelectedItem as Account).ChildAccount;
                    cmbZc2.DisplayMember = "Name"; // 显示的属性
                    cmbZc2.ValueMember = "Id"; // 实际值的属性
                    break;
                case "cmbSr1":
                    cmbSr2.DataSource = (cmbSr1.SelectedItem as Account).ChildAccount;
                    cmbSr2.DisplayMember = "Name"; // 显示的属性
                    cmbSr2.ValueMember = "Id"; // 实际值的属性
                    break;
                default:
                    break;
            }
        }
        #endregion

        private void tabMain_SelectedIndexChanged(object sender, EventArgs e)
        {

        }
    }
}
